package com.iqiyi.pps.epg.core.dao.record;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.record.TRecordChannelSignal;
import com.iqiyi.pps.epg.api.model.web.record.TRecordChannelSignalPage;
import com.iqiyi.pps.epg.api.model.web.record.TRecordSignalPage;
import com.iqiyi.pps.epg.core.dao.base.BaseDao;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.model.record.RecordChannelSignal;
import com.iqiyi.pps.epg.core.utils.SqlUtil;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.hibernate.type.StringType;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2018/4/11.
 */
@Component
public class RecordChannelSignalDao extends BaseDao<RecordChannelSignal> {


    public TRecordChannelSignalPage findChannelSignalPage(TPage page, TFilter filter) {
        String tempPattern = "${PARAMS}";
        String resultPattern = "recordChannelSignal.id, recordChannelSignal.signal_id, recordChannelSignal.channel_id, recordSignal.signal_name, recordSignal.signal_address , recordSignal.priority, recordSignal.server_cluster, recordChannelSignal.server_ip, recordChannel.channel_name, recordChannel.channel_code , recordChannelSignal.op_user, recordChannelSignal.create_time, recordChannelSignal.STATUS  ";
        String hql = "select " + tempPattern + " FROM record_channel_signal recordChannelSignal, record_channel recordChannel, record_signal recordSignal WHERE recordChannelSignal.status <> -1 AND recordChannelSignal.signal_id = recordSignal.id AND recordChannelSignal.channel_id = recordChannel.id ";
        String totalPattern = "COUNT(*) as total";
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        String original = page.getOrderBy();
        page.setOrderBy(rebuildOrderBy(original, "recordChannelSignal"));
        Page<TRecordSignalPage> dbPage = TransUtil.buildPage(page);
        String sql = SqlUtil.buildWithPropertyFilter(hql, filterList);
        boolean skipQuery = false;
        if (dbPage.isAutoCount()) {
            logger.debug("[build sql totalPattern]" + sql.replace(tempPattern, totalPattern));
            String totalCount = getSession().createSQLQuery(sql.replace(tempPattern, totalPattern))
                    .addScalar("total", new StringType()).list().get(0).toString();

            page.setTotalCount(Long.valueOf(totalCount));
            if (page.getTotalCount() == 0) {
                skipQuery = true;
                logger.debug("[skip query  case total is zero ]");
            }
        }

        List<TRecordChannelSignal> dataList = null;
        try {
            dataList = new ArrayList<>();
            if (!skipQuery) {
                sql = SqlUtil.buildAppendPage(dbPage, sql);
                sql = SqlUtil.buildAppendPageLimit(dbPage, sql);
                logger.debug("[build sql resultPattern ]" + sql.replace(tempPattern, resultPattern));
                String replaceSql = sql.replace(tempPattern, resultPattern);
                List result = getSession().createSQLQuery(replaceSql).list();
                TRecordChannelSignal singleData = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Object single : result) {
                    Object[] obj = (Object[]) single;
                    singleData = new TRecordChannelSignal();
                    singleData.setId(Long.valueOf("" + obj[0]));
                    singleData.setSignalId(Long.valueOf("" + obj[1]));
                    singleData.setChannelId(Long.valueOf("" + obj[2]));
                    singleData.setSignalName(obj[3] == null ? null :""+obj[3]);
                    singleData.setSignalAddress(obj[4] == null ? null :""+obj[4]);
                    singleData.setPriority(Integer.valueOf(""+obj[5]));
                    singleData.setServerCluster(obj[6] == null ? null :""+obj[6]);
                    singleData.setServerIp(obj[7] == null ? null :""+obj[7]);
                    singleData.setChannelName(obj[8] == null ? null :""+obj[8]);
                    singleData.setChannelCode(obj[9] == null ? null :""+obj[9]);
                    singleData.setOpUser(obj[10] == null ? null :""+obj[10]);
                    singleData.setCreateTime(sdf.format(obj[11]));
                    singleData.setStatus(Integer.valueOf("" + obj[12]));

                    dataList.add(singleData);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("findSignalPage[exception]{}", e);
        }
        TRecordChannelSignalPage libraryPage = new TRecordChannelSignalPage();
        page.setOrderBy(original);
        libraryPage.setTPage(page);
        libraryPage.setResult(dataList);
        return libraryPage;
    }


    public int getServerIpSumByServerIp(String serverIp) {
        try {
            String sql = "SELECT COUNT(*) FROM `record_channel_signal` WHERE server_ip = ? AND `status` = 1;";
            String result = getSession().createSQLQuery(sql).setString(0, serverIp).list().get(0).toString();
            return Integer.parseInt(result);
        } catch (Exception e) {
            logger.error("getServerIpSumByServerIp[exception]{}", e);
            return 0;
        }


    }


    private String rebuildOrderBy(String original, String aliasName) {
        String[] params = original.split(",");
        StringBuilder sBuilder = new StringBuilder();
        for (String param : params) {
            sBuilder.append(aliasName + "." + param);
            sBuilder.append(",");
        }
        if (sBuilder.length() > 0) {
            sBuilder.deleteCharAt(sBuilder.length() - 1);
        }
        return sBuilder.toString();
    }

}
